<?php

namespace app\admin\controller;

use think\Db;

class ExtendFunction extends Common
{
    public function list()
    {
        $where = [];

        $search_name = input('param.name');
        $search_type = input('param.type');

        if ($search_name && $search_type) {
            $where[$search_type] = ['like', '%' . $search_name . '%'];
        }


        $data = db('extend_function')->where($where)->order('sort desc,id asc')->paginate(_getCachePages(), false, ['query' => request()->param()]);
        $page = $data->render();

        $this->assign('data', $data);
        $this->assign('page', $page);

        return $this->fetch();
    }
    public function add()
    {
        $id = input("id");

        if (request()->isAjax()) {
            $post = input('post.');

            if (!$id) {
                $has = Db::name('extend_function')->where(['name'=>$post['name']])->find();
                if ($has) return ['err'=>'名称已存在'];
                $res = Db::name('extend_function')->insert($post);

                $data = $res ? ['ret' => '添加成功'] : ['err' => '添加失败'];
            } else {
                $res = Db::name('extend_function')->where('id', $id)->update($post);

                $data = $res ? ['ret' => '修改成功'] : ['err' => '修改失败'];
            }
        } else {
            if ($id) {
                $name = Db::name('extend_function')->find($id);

                if ($name) {
                    $this->assign('name', $name);
                } else {
                    return ['err' => 'id参数错误'];
                }
            }
            $data = $this->fetch();
        }
        return $data;
    }

    public function del()
    {
        if (request()->isAjax()) {
            $pid = input('id');
            if ($pid) {
                $res = Db::name('extend_function')->delete($pid);
                if ($res) {
                    $data = ['ret' => '删除成功'];
                } else {
                    $data = ['err' => '删除失败'];
                }
            } else {
                $data = ['err' => 'id参数错误'];
            }
        } else {
            $data = ['err' => '提交参数错误'];
        }
        return $data;
    }
}